/*
 * @Author: xiaohao
 * @Date: 2025-10-28 22:27:20
 * @LastEditors: xiaohao
 * @LastEditTime: 2025-11-04 17:10:45
 * @FilePath: /Project/ConcurrentMemoryPool/test/unit/unit_ObjectPool.cpp
 * @Description:
 */
#include "ConcurrentMemoryPool/ObjectPool.h"

struct TreeNode
{
    int _val;
    TreeNode *_left;
    TreeNode *_right;
    TreeNode()
        : _val(0), _left(nullptr), _right(nullptr)
    {
    }
};

// 测试对象池性能的函数
void TestObjectPool()
{
    // 测试参数
    const size_t Rounds = 3; // 测试轮次（重复申请释放的次数）
    const size_t N = 100000; // 每轮申请释放的对象数量（10万个）

    // 第一组：测试普通new/delete的性能
    size_t begin1 = clock();
    std::vector<TreeNode *> v1;
    v1.reserve(N);
    for (size_t j = 0; j < Rounds; ++j)
    {
        // 申请N个对象
        for (int i = 0; i < N; ++i)
        {
            v1.push_back(new TreeNode);
        }
        // 释放N个对象
        for (int i = 0; i < N; ++i)
        {
            delete v1[i];
        }
        v1.clear();
    }
    size_t end1 = clock();

    ObjectPool<TreeNode> TNPool;
    size_t begin2 = clock();
    std::vector<TreeNode *> v2;
    v2.reserve(N);
    for (size_t j = 0; j < Rounds; ++j)
    {
        for (int i = 0; i < N; ++i)
        {
            v2.push_back(TNPool.New()); // 对象池New：复用内存或切割大块内存+调用构造函数
        }
        for (int i = 0; i < 100000; ++i)
        {
            TNPool.Delete(v2[i]); // 对象池Delete：调用析构函数+加入自由链表
        }
        v2.clear();
    }
    size_t end2 = clock();

    // 输出性能对比结果（时间单位：时钟周期）
    std::cout << "new cost time:" << end1 - begin1 << std::endl;
    std::cout << "object pool cost time:" << end2 - begin2 << std::endl;
}

int main()
{
    TestObjectPool();
    return 0;
}